package com.lysj.admin.master.bussiness.company.company.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lysj.admin.master.bussiness.admin.domain.CompanyProviderBind;
import com.lysj.admin.master.bussiness.company.company.domain.CommissionApply;
import com.lysj.admin.master.bussiness.company.company.domain.CommissionDetail;
import com.lysj.admin.master.bussiness.company.company.domain.Employee;
import com.lysj.admin.master.bussiness.company.company.mapper.CommissionDetailMapper;
import com.lysj.admin.master.bussiness.company.company.vo.EmployeeCommissionVO;
import com.lysj.admin.master.common.exception.BaseException;
import com.lysj.admin.master.common.spring.mpbase.MyService;
import com.lysj.admin.master.common.spring.pagination.PageRequestDTO;
import com.lysj.admin.master.common.web.ParamUtil;
import com.lysj.admin.master.common.web.Resp;
import com.lysj.admin.master.common.web.RespUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Created by drj on 2019-12-27 16:24
 * @description
 */
@Slf4j
@Service
@Transactional
public class CommissionDetailService extends MyService<CommissionDetailMapper, CommissionDetail> {

    @Resource
    private EmployeeService employeeService;
    @Resource
    private CommissionApplyService commissionApplyService;

    /**
     * @author Created by zk on 2020/1/14 14:59
     * @Description 根据申请ID修改状态
     */
    @Transactional
    public void updateCommissionStatusByApplyId(String applyId, CommissionDetail.CommissionStatus status) {
        if (applyId != null && status != null) {
            UpdateWrapper<CommissionDetail> wrapper = new UpdateWrapper<>();
            wrapper.lambda()
                    .eq(CommissionDetail::getCommissionApplyId, applyId)
                    .set(CommissionDetail::getCommissionStatus, status.getCode());
            this.update(wrapper);
        } else {
            throw new BaseException(Resp.ResStatus.PARAM_ERROR, "请提供完整的申请信息和状态信息");
        }
    }

    public List<EmployeeCommissionVO> findEmployeeCommissionList(String employeeId, Integer commissionStatus) {
        Employee employee = employeeService.getById(employeeId);
        List<EmployeeCommissionVO> employeeCommissionVOS = new ArrayList<>();
        if (employee != null && !ParamUtil.isBlank(employee.getIdNum()) && !ParamUtil.isBlank(employee.getPhone())) {
            QueryWrapper<CommissionDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("id_num", employee.getIdNum());
            wrapper.eq("phone", employee.getPhone());
            wrapper.eq(commissionStatus != null, "commission_status", commissionStatus);
            employeeCommissionVOS = this.getBaseMapper().findEmployeeCommissionList(wrapper);
        }
        employeeCommissionVOS = employeeCommissionVOS.parallelStream()
                .filter(vo -> !CommissionDetail.CommissionStatus.NO_GRANT.getCode().equals(vo.getCommissionStatus()))
                .collect(Collectors.toList());
        return employeeCommissionVOS;
    }

    public Page<EmployeeCommissionVO> findCommissionDetailList(Integer commissionStatus, PageRequestDTO pageRequestDTO) {
        Page<CommissionDetail> page = new Page<>(pageRequestDTO.getPageNumber(), pageRequestDTO.getPageSize());
        QueryWrapper<CommissionDetail> wrapper = new QueryWrapper<>();
        wrapper.eq(commissionStatus != null, "commission_status", commissionStatus);
        wrapper.orderByDesc("a.create_time");
        return this.getBaseMapper().findCommissionDetailList(wrapper, page);
    }


    public EmployeeCommissionVO employeeCommissionDetail(String detailId) {
        QueryWrapper<CommissionDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("a.id", detailId);
        return this.getBaseMapper().employeeCommissionDetail(wrapper);
    }

    @Transactional
    public void finishCommission(String detailId) {
        if (ParamUtil.isBlank(detailId)) {
            throw new BaseException(Resp.ResStatus.PARAM_ERROR, "缺失任务信息或凭证信息");
        }
        CommissionDetail commissionDetail = this.getById(detailId);
        if (commissionDetail == null) {
            throw new BaseException(Resp.ResStatus.PARAM_ERROR, "该任务不存在");
        }
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("id_num", commissionDetail.getIdNum());
        wrapper.eq("phone", commissionDetail.getPhone());
        Employee employee = employeeService.getOne(wrapper);
        if (employee == null) {
            throw new BaseException(Resp.ResStatus.PARAM_ERROR, "查无该任务对应的用户");
        }
        employee.setBalance(employee.getBalance().add(commissionDetail.getActPayPrice()));
        commissionDetail.setCommissionStatus(CommissionDetail.CommissionStatus.FINISH.getCode());
        //查询还有多少未完成的子订单
        Integer count = this.lambdaQuery()
                .eq(CommissionDetail::getCommissionApplyId, commissionDetail.getCommissionApplyId())
                .ne(CommissionDetail::getCommissionStatus, CommissionDetail.CommissionStatus.FINISH.getCode())
                .count();
        //若没有未完成的子订单，则标注已完成状态
        if (count == 0) {
            CommissionApply apply = commissionApplyService.getById(commissionDetail.getCommissionApplyId());
            apply.setCompleteTime(new Date());
            apply.setCostStatus(CommissionApply.CostStatus.FINISH.getCode());
            commissionApplyService.updateById(apply);
        }
        employeeService.updateById(employee);
        this.updateById(commissionDetail);
    }
}
